﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Autodesk.Revit.DB;

namespace YArchitech.Revit.MEP.Opening
{
	public class LinkFile
	{
		public ExternalFileReferenceType FlieType { get; set; }

		public string FileName { get; set; }

		public LinkFile(string fileName, ExternalFileReferenceType type)
		{
			this.FlieType = type;
			this.FileName = fileName;
		}

		public bool IsInvalid()
		{
			try
			{
				return new FileInfo(this.FileName).Exists;
			}
			catch
			{
			}
			return false;
		}

		public static List<LinkFile> GetLinkFiles(Autodesk.Revit.DB.Document doc)
		{
			List<LinkFile> result;
			try
			{
				List<LinkFile> list = new List<LinkFile>();
				foreach (Autodesk.Revit.DB.Document document in LinkFile.GetLinkDocs(doc))
				{
                    LinkFile linkFile = new LinkFile(document.PathName, (ExternalFileReferenceType)1);
					if (linkFile.IsInvalid())
					{
						list.Add(linkFile);
					}
				}
				result = list;
			}
			catch (Exception ex)
			{
				throw ex;
			}
			return result;
		}

		public static List<Document> GetLinkDocs(Autodesk.Revit.DB.Document doc)
		{
			List<Document> list = new List<Document>();
			try
			{
				foreach (RevitLinkInstance revitLinkInstance in ((IEnumerable<RevitLinkInstance>)new FilteredElementCollector(doc).OfClass(typeof(RevitLinkInstance)).Cast<RevitLinkInstance>().ToList<RevitLinkInstance>()))
				{
					Document linkDocument = revitLinkInstance.GetLinkDocument();
					if (linkDocument != null && !string.IsNullOrEmpty(linkDocument.PathName))
					{
						list.Add(linkDocument);
					}
				}
			}
			catch (Exception ex)
			{
				throw ex;
			}
			return list;
		}
	}
}
